//
//  CourseVC.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/4.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit

enum CourseType {
    case AwaitClasss //待上课
    case LookBackClass // 回放
}

class CourseVC: BCBaseVC {

    let headeeViewH: CGFloat = 30 // 区头的高度

    @IBOutlet weak var topView_H: NSLayoutConstraint!//整个上部图高度
    @IBOutlet weak var seachView_H: NSLayoutConstraint! //搜索区域高度
    @IBOutlet weak var seachView: UIView!
    @IBOutlet weak var vcTitle: UILabel!
    @IBOutlet weak var netState: UILabel!
    @IBOutlet weak var invateTextF: UITextField!
    @IBOutlet weak var courseTab: UITableView!
   
    private var pages: NSInteger = 0
    private let vm = CourseVM()
    private let disposeBag = DisposeBag()
    
    var courseType:CourseType  = .AwaitClasss
    var proView: BCProtocolView? // 协议的无数据view
    var noNetProView: BCProtocolView? // 协议的无网络view

    override func viewDidLoad() {
        super.viewDidLoad()
        vcTypeConfig()
        setUI()
        observeLoadData()
        lodeData()
        // 有新的webSocket消息
        NotificationCenter.default.addObserver(self, selector: #selector(notiCenterNewCourse), name: NSNotification.Name(rawValue: "testEventOnMessage"), object: nil)
    }
    
    override func lodeData() {
        switch courseType {
        case .AwaitClasss:
            vm.courseRequest(1) {
                self.bcTabView?.mj_header.endRefreshing()
            }
        default:
            vm.getHistoryPage(1) { [weak self] (pages) in
                self?.bcTabView?.mj_header.endRefreshing()
                if let rPages = pages, rPages > 1 {
                    self?.pages = rPages
                    self?.loadMoreData()
                }
            }
        }
        
    }
    
    override func loadMoreData() {
        vm.getPageCourses(offset: pages-1, 0) {
            self.pages -= 1
            if self.pages > 0 {
                self.bcTabView?.mj_footer.endRefreshing()
            } else {
                self.bcTabView?.mj_footer.endRefreshingWithNoMoreData()
            }
        }
    }
    
    @IBAction func seachBtnClick(_ sender: UIButton) {
        let searchVC = UIStoryboard.viewController(from: .CourseSB, viewControllerClass: SearchVC.self)
        searchVC.courseType = courseType
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    
    @IBAction func enterClick(_ sender: UIButton) {
        
    }
    
    
}

extension CourseVC: BCVCDataNetPro {
    
    fileprivate func setUI() {
        self.fd_prefersNavigationBarHidden = true //隐藏导航栏
        bcTabView = courseTab //设置tabView
        bcTabView?.bcHead = BCRefreshHeader { [weak self] in self?.lodeData() }
        if courseType == .LookBackClass {
            bcTabView?.bcFoot = BCRefreshFooter(refreshingBlock: { [weak self] in self?.loadMoreData() })
        }
        courseTab.rowHeight = 152
    }
    
    // 根据类型设置参数
    fileprivate func vcTypeConfig() {
        switch courseType {
        case .AwaitClasss:
            vcTitle.text = "待上课程"
            netState.isHidden = false
            seachView.isHidden = false
            seachView_H.constant = 50
            topView_H.constant = 100
        default:
            vcTitle.text = "课程回放"
            netState.isHidden = true
            seachView.isHidden = true
            seachView_H.constant = 0
            topView_H.constant = 50
        }
        
    }
    
    //监听有课程的变化
    @objc func notiCenterNewCourse() {
        lodeData()
    }
    // 监控数据 加载刷新
    fileprivate func observeLoadData() {
        vm.resultData.asObservable()
            .subscribe(onNext: { [weak self](resultData) in
                self?.courseTab.reloadData()
            }).disposed(by: disposeBag)
        
        BCUserManager.shareManager.Reachability_isNet.asObservable()
            .subscribe(onNext: { [weak self](isNet) in
                self?.setNoNetProView(isNet: isNet)
            }).disposed(by: disposeBag)
    }
    
    /// 无数据加载
    ///
    /// - Parameter dataCount: 数据数目
    fileprivate func setProView(dataCount: NSInteger) {
       
        if  proView == nil {
            let y = bcTopBarHeight + topView_H.constant 
            let h = kScreenHeight - y - bcTabBarHeight
            let frame = CGRect(x: 0, y: y, width: kScreenWidth, height: h)
            proView = loadBCProViewInVC(image: UIImage(named: "image_no_class"), alertText: "暂时没有课程哦～", frame: frame) //初始化协议view
        }
        
        if dataCount == 0 {
            // 无数据
            proView?.isHidden = false
        } else {
            proView?.isHidden = true
        }
        
    }
    
    /// 无网络加载
    ///
    /// - Parameter isNet: 是否有网
    fileprivate func setNoNetProView(isNet: Bool) {
        switch courseType {
        case .AwaitClasss:
            netState.isHidden = isNet
        default:
            if noNetProView == nil {
                let y = bcTopBarHeight + topView_H.constant
                let h = kScreenHeight - y - bcTabBarHeight
                let frame = CGRect(x: 0, y: y, width: kScreenWidth, height: h)
                noNetProView = loadBCNoNetProViewInVC(frame: frame) //初始化无网络协议view
                noNetProView?.refreshBtn?.addTarget(self, action: #selector(noNetRefreshClick(_:)), for: .touchUpInside)
            }
            noNetProView?.isHidden = isNet
        }
    }
    // 无网络的刷新按钮
    @objc fileprivate func noNetRefreshClick( _ sender: UIButton) {
        lodeData()
    }
}

extension CourseVC: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let list = vm.resultData.value[vm.mdArray[section]]
        return list?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "AwaitClassCell") as! AwaitClassCell
        cell.courseType = self.courseType
        let list = vm.resultData.value[vm.mdArray[indexPath.section]]
        let model = list?[indexPath.row]
        cell.awaitModel = model
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        setProView(dataCount: vm.mdArray.count)
        return vm.mdArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headeeViewH
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headview = UIView()
        headview.backgroundColor = UIColor.hex(hexString: "#F8F8F8")
        headview.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: headeeViewH)
        let labe = UILabel()
        labe.frame = CGRect(x: 15, y: 7, width: 200, height: 16)
        labe.textAlignment = .left
        let nowTime = String.getNowTimeString(format: .TimeType_Md)
        if vm.mdArray[section] == nowTime {
            labe.text = "今天"
        } else {
            labe.text = vm.mdArray[section]
        }
        headview.addSubview(labe)
        return headview
    }
}
